<template>
  <div style="flex: 90%; margin-top: 20px; margin-left: 20px">
    
    <el-form :inline="true" :model="data" class="demo-form-inline">
      <el-form-item label="股票代码">
        <el-input
          v-model="data.name"
          style="width: 240px"
          placeholder="input stock code"
          @update:model-value="onInputChange"
      /></el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      ref="tableRef"
      row-key="code"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="code" label="代码" width="180" />
      <el-table-column prop="currentPrice" label="价格" width="180"/>
      <el-table-column prop="isFoucus" label="操作" width="300" > 
        <template #default="scope">
          <el-button @click="handleBuySure(scope.$index, scope.row)" type="primary" >
          签字确认
          </el-button>
          <el-button  @click="handleFoucus(scope.$index, scope.row)" 
           :type="['','success','primary','danger'][scope.row.isFoucus]"  plain>
          {{ ['未关注','已关注','观察中','Vip关注'][scope.row.isFoucus]}}
          </el-button>
        </template>  
      </el-table-column>
      <el-table-column prop="type" label="类型" width="180">
        <template #default="scope">
          <el-select @change="handleType(scope.row, $event)"  v-model="[ '请选择',  '市场情绪龙', '市场趋势龙' ,'板块情绪龙' ,'板块趋势龙' ,'板块领涨龙' ,
 '市场老龙' , '板块老龙' ,'权重老龙' , '预期龙' , '避险龙', '杂毛' ][scope.row.shortNameType]" placeholder="Select" size="large" class="select" >
            <el-option v-for="item in options_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>  
      </el-table-column>

      <el-table-column prop="importantScore" label="权重" width="180">
        <template #default="scope">
          <el-select @change="handleScore(scope.row, $event)"  v-model="[ '0.5级', '1级',  '2级', '3级' ,'4级' ,'5级' ][scope.row.importantScore]" placeholder="Select" size="large" class="select" >
            <el-option v-for="item in score_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>  
      </el-table-column>
    </el-table>

  </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { TableColumnCtx, TableInstance } from "element-plus";
import { reactive } from "vue";
import axios from "axios";
import { countdownEmits, ElMessage, ElMessageBox} from "element-plus";
import ClipboardJS from 'clipboard';
import { useStore } from 'vuex';
import type { Action } from 'element-plus'

const data = reactive({
  name: "",
});

const onSearh = (str: string, type: number) => {
  console.log("submit!");
  const encodedName = encodeURIComponent(str);
  const api = "api/plat/stockNowPrice/getStockListByName?name=" + encodedName;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onSubmit_UpdateOrder = (pid: number,pstatus:number) => {
  axios.put("api/plat/stockOrder/update", {
    id:pid,
    status:pstatus,
  }).then((response) => {
    console.log(response);
    if (response.data.status == 200) {
        ElMessage({
          message: "签字完成",
          type: "success",
        });
      } else {
        ElMessage({
          message: "签字失败",
          type: "success",
        });
      }
  })
}

const onUpdateFoucus = (id: number, focus: number) => {
  console.log("submit!");
  axios
    .put("api/plat/stockNowPrice/update", {
      id: id,
      isFoucus: focus,
    })
    .then((response) => {
      // console.log(response.status);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onUpdate = (params) => {
  console.log("submit!");
  axios
    .put("api/plat/stockNowPrice/update", params)
    .then((response) => {
      // console.log(response.status);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

interface StockNowPrice {
  id: number;
  name: string;
  TSCODE: string;
  isFoucus: number;
  shortName: string;
  shortNameType: number;
  importantScore: number;
}

const onInputChange = (newValue, oldValue) => {
  console.log("Input changed:", newValue);
  const containsChinese = /[\u4e00-\u9fa5]/.test(newValue);
  if (containsChinese) {
    onSearh(newValue, 2);
  } else if (newValue.length == 6) {
    onSearh(newValue, 1);
  }
};

const handleDateChange = (val) => {
    console.log('选择了新的日期/时间:', val);
    const date = new Date(val)
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1
    const day = ('0' + date.getDate()).slice(-2);
    const dayTime = `${year}-${month}-${day}`;
    console.log('选择了新的日期/时间:', dayTime);

};

const handleFoucus = (index: number, row: StockNowPrice) => {
  console.log(index, row)
  if (row.isFoucus == 0) {
    row.isFoucus = 1;
  } else  {
    row.isFoucus = 0;
  } 
  onUpdateFoucus(row.id, row.isFoucus);
}

const handleType = (row: StockNowPrice, value) => {
  onUpdate({
    id: row.id,
    shortNameType: value,
    shortName: getShortNameType(value)
  })
  setTimeout(() => {
        console.log('延迟执行的代码');
        // 在这里执行你需要延迟的操作
        onSearh(data.name, 2);
      }, 200); // 延迟2秒执行
}

const handleScore = (row: StockNowPrice, value) => {
  onUpdate({
    id: row.id,
    importantScore: value
  })
  setTimeout(() => {
        console.log('延迟执行的代码');
        // 在这里执行你需要延迟的操作
        onSearh(data.name, 2);
      }, 200); // 延迟2秒执行
}

const loading = ref(false);
const tableRef = ref<TableInstance>();

const tableData = ref([]);

const store = useStore();

const value_type ='短线风格'
const options_type = [
                { value: '0',label: '请选择', },
                { value: '1',label: '市场情绪龙', },
                { value: '2',label: '市场趋势龙' },

                { value: '3',label: '板块情绪龙' },
                { value: '4',label: '板块趋势龙' },
                { value: '5',label: '板块领涨龙' },

                { value: '6',label: '市场老龙' },
                { value: '7',label: '板块老龙' },
                { value: '8',label: '权重老龙' },
                
                { value: '9',label: '预期龙' },
                { value: '10',label: '避险龙' },
                { value: '11',label: '杂毛', },
            ]
const getShortNameType = (value) => {
  return options_type[value].label; 
}

const score_type = [
                { value: '5',label: '5级', },
                { value: '4',label: '4级', },
                { value: '3',label: '3级' },

                { value: '2',label: '2级' },
                { value: '1',label: '1级' },
                { value: '0',label: '0.5级' },
            ]

var code = ''
onMounted(() => {
      const clipboard = new ClipboardJS('.btn-copy', {
        text: () => code
      });

      clipboard.on('success', (e) => {
        console.log('Text copied to clipboard');
        e.clearSelection();
      });

      clipboard.on('error', (e) => {
        console.error('Failed to copy text: ', e);
      });
    });

    const handleBuySure = (index: number, row: StockNowPrice) => {
      ElMessageBox.alert('请遵守交易记录，切勿随心操作，挣钱不易', '签字确认', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: '确定',
    center:true,
    callback: (action: Action) => {
      onSubmit_UpdateOrder(row.id, 10)
    },
  })
    };

</script>
  
